package values

import (
	"fmt"

	"soluty.cc/go/xlog"
)

// 属性之间的正交性()
type Attribute struct {
	attrs  map[string]*Number
	holder interface{}
	nth    int32
	env    Formula
	err    error
}

func NewAttribute(holder interface{}, nth int32) *Attribute {
	a := &Attribute{
		holder: holder,
		attrs:  map[string]*Number{},
		nth:    nth,
	}
	return a
}

func (a *Attribute) Error() error {
	return a.err
}

func (a *Attribute) String() string {
	var s string
	for k, value := range a.attrs {
		s += fmt.Sprintf("%v_%v\n", k, value)
	}
	return s
}

func (a *Attribute) AddNumber(name string, v int32, minmax ...int32) *Attribute {
	if a.attrs[name] != nil {
		a.err = xlog.Errorf(xlog.Fmt(), "", fmt.Errorf("重复的属性%v", name))
		return a
	}
	n := newNumber(a.nth, a.holder, minmax...)
	n.setFormula(a.env)
	n.SetBase(v)
	a.attrs[name] = n
	return a
}

func (a *Attribute) Attr(name string) *Number {
	return a.attrs[name]
}

func (a *Attribute) update() error {
	var e error
	for name, attr := range a.attrs {
		err := attr.update()
		if err != nil {
			e = xlog.Errorf(xlog.Fmt(), fmt.Sprintf("属性名：%v",name), err)
			continue
		}
	}
	return e
}

func (a *Attribute) SetFormula(formula Formula) error{
	for _, attr := range a.attrs {
		attr.setFormula(formula)
	}
	err := a.update()
	if err != nil {
		return xlog.Errorf(xlog.Fmt(),"", err)
	}
	return nil
}

func (a *Attribute) Reset() error {
	err := a.SetFormula(nil)
	if err != nil {
		return xlog.Errorf(xlog.Fmt(),"", err)
	}
	return nil
}